package com.yakaten.logic;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.seasar.extension.jdbc.SqlBatchUpdate;
import org.seasar.extension.jdbc.SqlUpdate;
import org.seasar.framework.beans.util.BeanMap;
import org.seasar.framework.util.ResourceUtil;

import com.yakaten.dto.AmazonPriceTaskDto;
import com.yakaten.exception.SystemException;
import com.yakaten.service.JdbcManagerFactory;

/**
 * 
 *
 */
public class AmazonPriceLogic extends JdbcManagerFactory {

	private static final String TABLE_NAME = "amazon_task";
	
	private static final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	private static final String TASK_FILE_NAME_KEY="system.task.file.amazon";
	
	static Logger logger = Logger.getLogger(AmazonPriceLogic.class);

	public String readExistData() throws SystemException {
		int allCount =0;
		int badCount =0;
		
		String taskFile = ResourceUtil.getProperties("yakaten.properties")
				.getProperty(TASK_FILE_NAME_KEY);

		InputStreamReader ir = null;
		try {
			ir = new InputStreamReader(new FileInputStream(
					taskFile), "shift_jis");

			BufferedReader br = new BufferedReader(ir);
			String current = "";
			while ((current = br.readLine()) != null) {
				String data[] =current.split(",");
				AmazonPriceTaskDto dto = new AmazonPriceTaskDto();
				dto.setTaskNo(data[0]);
				dto.setAmazonItemId(data[1]);
				dto.setAmazonItemName(data[2]);
				dto.setAmazonItemPrice(Long.parseLong(data[3]));
				dto.setShopItemId(data[4]);
				dto.setShopItemName(data[5]);
				dto.setShopItemPrice(Long.parseLong(data[6]));
				dto.setStartPrice(Long.parseLong(data[7]));
				dto.setMinPrice(Long.parseLong(data[8]));
				dto.setStartTime(sf.parse(data[9]));
				dto.setStatus(Long.parseLong(data[10]));
				dto.setQuantity(data[11]);
				dto.setCondition(data[12]);
				
				try{
					addTask(dto);
				}catch(Exception e){
					logger.error("bad data:"+dto);
					badCount++;
				}
				
				allCount++;
			}
		} catch (Exception e) {
			throw new SystemException(e);
		}finally{
			if(ir!=null){
				try {
					ir.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "allcount : "+allCount +",badcount : "+badCount;
	}
	/**
	 * 
	 * @return
	 * @throws SystemException
	 */
	public List<AmazonPriceTaskDto> getAllTaskList() throws SystemException {
		List<AmazonPriceTaskDto> resultList = new ArrayList<AmazonPriceTaskDto>();

		List<BeanMap> result = jdbcManager.selectBySql(BeanMap.class,
				"SELECT * FROM " + TABLE_NAME).getResultList();

		for (BeanMap current : result) {
			AmazonPriceTaskDto dto = new AmazonPriceTaskDto();
			dto.setTaskNo((String) current.get("taskno"));
			dto.setAmazonItemId((String) current.get("amazonitemid"));
			dto.setAmazonItemName((String) current.get("amazonitemname"));
			dto
					.setAmazonItemPrice(((BigDecimal) current
							.get("amazonitemprice")).longValue());
			dto.setShopItemId((String) current.get("shopitemid"));
			dto.setShopItemName((String) current.get("shopitemname"));
			dto.setShopItemPrice(((BigDecimal) current.get("shopitemprice"))
					.longValue());
			dto.setStartPrice(((BigDecimal) current.get("startprice"))
					.longValue());
			dto.setMinPrice(((BigDecimal) current.get("minprice")).longValue());
			dto.setStartTime((Date) current.get("starttime"));
			dto.setStatus(Long.parseLong((String) current.get("status")));
			dto.setQuantity(""
					+ ((BigDecimal) current.get("quantity")).longValue());
			dto.setCondition((String) current
					.get("itemcondition"));

			resultList.add(dto);
		}
		return resultList;
	}

	/**
	 * 
	 * @param amazonItemId
	 * @param shopItemId
	 * @return
	 * @throws SystemException
	 */
	public boolean isExistTask(String shopItemId)
			throws SystemException {
		boolean isExit = false;

		List<BeanMap> result = jdbcManager.selectBySql(
				BeanMap.class,
				"SELECT * FROM " + TABLE_NAME
						+ " where  shopItemId = ?",
				shopItemId).getResultList();

		if (result != null && result.size() > 0) {
			isExit = true;
		}

		return isExit;
	}

	/**
	 * 
	 * @return
	 * @throws SystemException
	 */
	public String getNewTaskNo() throws SystemException {
		String newTaskNo = "1";

		BeanMap result = jdbcManager.selectBySql(
				BeanMap.class,
				"SELECT max(cast(taskNo as SIGNED)) +1 newTaskNo FROM "
						+ TABLE_NAME).getSingleResult();

		if (result != null) {
			newTaskNo = ((Long) result.get("newtaskno")).toString();
		}

		return newTaskNo;
	}

	/**
	 * 
	 * @param dto
	 * @return
	 * @throws SystemException
	 */
	public boolean addTask(AmazonPriceTaskDto dto) throws SystemException {
		boolean result = false;
		String sql = "INSERT INTO " + TABLE_NAME
				+ " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)";
		SqlUpdate batchUpdate = jdbcManager.updateBySql(sql, String.class,
				String.class, String.class, Integer.class, String.class,
				String.class, Integer.class, Integer.class, Integer.class,
				Date.class, String.class, Integer.class, String.class);
		batchUpdate.params(dto.getTaskNo(), dto.getAmazonItemId(), dto
				.getAmazonItemName(), dto.getAmazonItemPrice(), dto
				.getShopItemId(), dto.getShopItemName(),
				dto.getShopItemPrice(), dto.getStartPrice(), dto.getMinPrice(),
				dto.getStartTime(), dto.getStatus(), dto.getQuantity(), dto.getCondition());

		try {
			int re = batchUpdate.execute();
			if (re == 1) {
				result = true;
			}
		} catch (Exception e) {
			throw new SystemException(e);
		}

		return result;
	}

	/**
	 * 
	 * @param dataList
	 * @return
	 * @throws SystemException
	 */
	public boolean updateTask(List<AmazonPriceTaskDto> dataList)
			throws SystemException {
		boolean result = false;

		String sql = "update " + TABLE_NAME + " set " + "amazonItemId = ? "
				+ ",amazonItemName = ? " + ",amazonItemPrice = ? "
				+ ",shopItemId = ? " + ",shopItemName = ? "
				+ ",shopItemPrice = ? " + ",startPrice = ? " + ",minPrice = ? "
				+ ",startTime = ? " + ",status = ? " + ",quantity = ? "
				+ ",itemCondition = ? " + "where taskNo = ?";

		SqlBatchUpdate batchUpdate = jdbcManager.updateBatchBySql(sql,
				String.class, String.class, Integer.class, String.class,
				String.class, Integer.class, Integer.class, Integer.class,
				Date.class, String.class, Integer.class, String.class,
				String.class);

		for (AmazonPriceTaskDto current : dataList) {
			batchUpdate.params(current.getAmazonItemId(), current
					.getAmazonItemName(), current.getAmazonItemPrice(), current
					.getShopItemId(), current.getShopItemName(), current
					.getShopItemPrice(), current.getStartPrice(), current
					.getMinPrice(), current.getStartTime(),
					current.getStatus(), current.getQuantity(), current
							.getCondition(), current
							.getTaskNo());
		}

		try {
			int[] res = batchUpdate.execute();
			result = true;
		} catch (Exception e) {
			throw new SystemException(e);
		}

		return result;
	}

	/**
	 * 
	 * @param updateDto
	 * @return
	 * @throws SystemException
	 */
	public synchronized boolean updateTask(AmazonPriceTaskDto updateDto)
			throws SystemException {
		boolean result = false;

		String sql = "update " + TABLE_NAME + " set " + "amazonItemId = ? "
				+ ",amazonItemName = ? " + ",amazonItemPrice = ? "
				+ ",shopItemId = ? " + ",shopItemName = ? "
				+ ",shopItemPrice = ? " + ",startPrice = ? " + ",minPrice = ? "
				+ ",startTime = ? " + ",status = ? " + ",quantity = ? "
				+ ",itemCondition = ? " + "where taskNo = ?";

		SqlUpdate sqlUpdate = jdbcManager.updateBySql(sql, String.class,
				String.class, Integer.class, String.class, String.class,
				Integer.class, Integer.class, Integer.class, Date.class,
				String.class, Integer.class, String.class, String.class);

		sqlUpdate.params(updateDto.getAmazonItemId(), updateDto
				.getAmazonItemName(), updateDto.getAmazonItemPrice(), updateDto
				.getShopItemId(), updateDto.getShopItemName(), updateDto
				.getShopItemPrice(), updateDto.getStartPrice(), updateDto
				.getMinPrice(), updateDto.getStartTime(),
				updateDto.getStatus(), updateDto.getQuantity(), updateDto
						.getCondition(), updateDto.getTaskNo());

		try {
			int res = sqlUpdate.execute();
			if (res == 1) {
				result = true;
			}

		} catch (Exception e) {
			throw new SystemException(e);
		}

		return result;
	}

	/**
	 * 
	 * @param taskNo
	 * @return
	 * @throws SystemException
	 */
	public synchronized boolean deleteTask(String taskNo)
			throws SystemException {
		boolean result = false;

		String sql = "delete from " + TABLE_NAME + " where taskNo = ?";

		SqlUpdate sqlUpdate = jdbcManager.updateBySql(sql, String.class);

		sqlUpdate.params(taskNo);

		try {
			int res = sqlUpdate.execute();
			if (res == 1) {
				result = true;
			}

		} catch (Exception e) {
			throw new SystemException(e);
		}

		return result;
	}

	/**
	 * 
	 * @param taskNo
	 * @param status
	 * @return
	 * @throws SystemException
	 */
	public synchronized boolean updateTaskStatus(String taskNo, long status)
			throws SystemException {
		boolean result = false;

		String sql = "update " + TABLE_NAME
				+ " set  status = ?  where taskNo = ?";

		SqlUpdate sqlUpdate = jdbcManager.updateBySql(sql, String.class,
				String.class);

		sqlUpdate.params(status, taskNo);

		try {
			int res = sqlUpdate.execute();
			if (res == 1) {
				result = true;
			}

		} catch (Exception e) {
			throw new SystemException(e);
		}

		return result;
	}

	public static void main(String[] args) {
		try {

			AmazonPriceLogic logic = new AmazonPriceLogic();

			AmazonPriceTaskDto dto = new AmazonPriceTaskDto();
			dto.setTaskNo("3");
			dto.setAmazonItemId("K0000305715");
			dto.setAmazonItemName("MacBook Pro 2400/15.4 MD322J/A");
			dto.setAmazonItemPrice(119620);
			dto.setShopItemId("005006000028");
			dto.setShopItemName("パナソニック Let's note SX1 CF-SX1GEBDR [ブラック]");
			dto.setShopItemPrice(119621);
			dto.setStartPrice(999999);
			dto.setMinPrice(1);
			dto.setStartTime(new Date());
			dto.setStatus(1);
			dto.setQuantity("1");
			dto.setCondition("1");
			System.out.println(logic.addTask(dto));
//			 System.out.println(logic.getNewTaskNo());
//			 System.out.println(logic.getAllTaskList().get(0));
//			 System.out.println(logic.isExistTask("K0000305715","005006000028"));
//			 System.out.println(logic.getNewTaskNo());

			AmazonPriceTaskDto dto1 = new AmazonPriceTaskDto();
			dto1.setTaskNo("3");
			dto1.setAmazonItemId("-K0000305715");
			dto1.setAmazonItemName("-MacBook Pro 2400/15.4 MD322J/A");
			dto1.setAmazonItemPrice(888);
			dto1.setShopItemId("-005006000028");
			dto1.setShopItemName("-パナソニック Let's note SX1 CF-SX1GEBDR [ブラック]");
			dto1.setShopItemPrice(888);
			dto1.setStartPrice(888);
			dto1.setMinPrice(888);
			dto1.setStartTime(new Date());
			dto1.setStatus(7);
			dto1.setQuantity("888");
			dto1.setCondition("2");

			List<AmazonPriceTaskDto> updataList = new ArrayList<AmazonPriceTaskDto>();
//			updataList.add(dto1);
//			 System.out.println(logic.deleteTask("3"));
//			 System.out.println(logic.updateTask(dto1));
//			System.out.println(logic.updateTaskStatus("3", 9));

		} catch (SystemException e) {
			e.printStackTrace();
		}
	}
}
